<template>
  <div class="addInviteConfig">
    <h2 class="editPage">{{ id ? "修改" : "新增" }}</h2>
    <a-card>
      <a-form :form="form">
        <a-form-item
          label="LOGO"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="prefix+'shop/upload/uploadImage/BRAND'"
            :headers="{'Authorization': token}"
            :before-upload="beforeUpload"
            @change="handleChange"
            
          >
            <img style="width:100px;height:100px" v-if="postUserData.logoPath" :src="imgUrl+postUserData.logoPath" alt="avatar" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item
          label="品牌名称"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-input
            placeholder="请输入品牌名称"
            @change="brandNameChange"
            v-decorator="[
              'brandName',
              {
                rules: [{ required: true, message: '请输入品牌名称' }],
              },
            ]"
          ></a-input>
        </a-form-item>

        <a-form-item
          label="品牌介绍"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-textarea 
            placeholder="请输入品牌介绍"
            allow-clear
            @change="onChange"
             v-decorator="[
              'introduction',
              {
                rules: [{ required: true, message: '请输入品牌名称' }],
              },
            ]"
          />
        </a-form-item>

        <a-form-item
          label="关键词"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-input
            placeholder="请输入关键词"
            @change="keywordsChage"
            v-decorator="[
              'keywords',
              {
                rules: [{ required: true, message: '请输入关键词' }],
              },
            ]"
          ></a-input>
        </a-form-item>

        <div>
          <a-button
            type="primary"
            class="marginBtn"
            @click="AddInviteConfigAction"
            >确定</a-button
          >
          <a-button @click="$router.go(-1)" class="marginBtn">返回</a-button>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import { prefix, imgUrl } from '@/utils/env-setup'
import * as API from "../../api/brand";
import { mapState } from "vuex";
import editor from "../../commonComponents/editor/editor";
import address from "../../utils/cascader";

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default {
  name: "inviteConfig",
  data() {
    return {
      prefix,
      imgUrl,
      loading: false,
      imageUrl: "",
      // Info: {},
      address: {},
      rolesList: ["旗舰店", "专卖店", "自营店"],
      form: this.$form.createForm(this),
      num: 0,
      id: null,
      loading: false,
      postUserData: {},
      agentLevelList: [
        { value: "ONE", label: "一级" },
        { value: "TWO", label: "二级" },
        { value: "THREE", label: "三级" },
      ],
      rewardTypeList: [
        { value: "SJ_JL", label: "升级奖励" },
        { value: "YJ_JL", label: "佣金奖励" },
      ],
      previewVisible: false,
      previewImage: "",
      fileList: [],
      previewVisibleIos: false,
      previewImageIos: "",
      fileListIos: [],
      url: "",
    };
  },
  components: {
    editor,
  },
  computed: {
    ...mapState({
      token: (state) => state.user.token,
    }),
  },
  mounted() {
    this.getbrandInfo();
  },
  created() {
    this.id = this.$route.query.id || null;
    console.log(this.id, "sssssssssssss");
   
  },

  activated() {},
  methods: {

    //图片上传
    handleChange(info) {
      console.log(info);
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file && (info.file.status === 'done')) {
        this.postUserData.logoPath = info.file?info.file.response.data.path : ''
        this.loading = false;
      }
      // if (info.file.status === "done") {
      //   getBase64(info.file.originFileObj, (imageUrl) => {
      //     this.imageUrl = imageUrl;
      //     this.loading = false;
      //   });
      // }
    },
    //图片上传
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    setFields(submitData) {
      // this.postUserData.brandName = submitData.brandName;
      // this.postUserData.keywords = submitData.keywords
      // this.postUserData.logoPath = submitData.logoPath;
      // this.postUserData.introduction = submitData.introduction;
      // this.postUserData.logoPath = submitData.logoPath;
      this.form.setFieldsValue({
        brandName: submitData.brandName,
        keywords: submitData.keywords,
        logoPath:submitData.logoPath,
        introduction:submitData.introduction
      });
    },
    //详情
    getbrandInfo() {
      if (this.id) {
        API.brandInfo(this.id).then((res) => {
          this.postUserData = res.data;
          // console.log(this.Info);
          this.setFields(res.data);
        });
      }
    },

    onChange(e) {
      this.postUserData.introduction = e.target.value
     
    },
    roleChange(value) {
      this.postUserData.merchantType = value;
      // console.log(value, 5555);
    
    },
  
    editorActon(editorContent) {
      this.postUserData.remark = editorContent;
    },

    AddInviteConfigAction() {
      this.form.validateFields((err) => {
        if (!err) {
          this.id ? this.edit() : this.add();
          //  this.add();
        }
      });
    },
    //新增
    add() {
      console.log(this.postUserData);
      this.loading = true;
      API.brandCreate(this.postUserData)
        .then((res) => {
          if (res.code === 200) {
            // this.$message.destroy();
            this.$message.success("添加成功");
            this.$router.go(-1);
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //修改
    edit() {
      this.loading = true;
      console.log(this.postUserData, "sssssssssssss");
      API.brandEdit(this.id, this.postUserData)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("修改成功");
            this.$router.go(-1);
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    filterOption(input, option) {
      console.log(input, option);
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  
    // handleChange({ fileList }) {
    //   this.fileList = fileList;
    //   if (fileList[0] && fileList[0].status === "done") {
    //     this.postUserData.azImg = fileList[0] ? fileList[0].response.data : "";
    //   }
    // },
 
    //表单参数
    brandNameChange(e) {
      console.log(e.target.value);
      this.postUserData.brandName = e.target.value;
    },
    keywordsChage(e) {
      this.postUserData.keywords = e.target.value;
    },
  
  },
};
</script>
